package com.shikong.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shikong.blog.common.Response;
import com.shikong.blog.dao.AdminArticleDao;
import com.shikong.blog.dao.CategoryDao;
import com.shikong.blog.domain.dos.ArticleCategoryRelDO;
import com.shikong.blog.domain.dos.CategoryDO;
import com.shikong.blog.domain.mapper.ArticleCategoryRelMapper;
import com.shikong.blog.domain.mapper.CategoryMapper;
import com.shikong.blog.model.webvo.category.QueryCategoryListItemRspVO;
import com.shikong.blog.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: TODO
 **/
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryDO> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AdminArticleDao articleDao;

    @Autowired
    private ArticleCategoryRelMapper articleCategoryRelMapper;

    @Override
    public Response queryCategoryList() {
       //        获取文章总数
        Long articleTotalCount = articleDao.selectTotalCount();
        List<CategoryDO> categoryDOList = categoryDao.selectAllCategory();

        List<QueryCategoryListItemRspVO> list = null;
        if (!CollectionUtils.isEmpty(categoryDOList)) {
            list = categoryDOList.stream()
                    .map(p -> QueryCategoryListItemRspVO.builder()
                            .id(p.getId())
                            .name(p.getName())
                            .Count(getCound((p.getId())))
                            .build())
                    .collect(Collectors.toList());
        }
        /*返回分类列表和文章总数*/
        Map map = new HashMap();
        map.put("categoryList",list);
        map.put("articleCount",articleTotalCount);
        return Response.success(map);
    }

    //    根据id查询数量
    private Integer getCound(Long id) {
        QueryWrapper<ArticleCategoryRelDO> queryWrapper = new QueryWrapper();
        queryWrapper.eq("category_id", id);
        return articleCategoryRelMapper.selectCount(queryWrapper).intValue();
    }

}
